import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { useUserStore } from "./user"
import { delCartAPI, findNewCartListAPI, insertCartAPI } from "@/api/cart"

export const useCartStore = defineStore('cart', () => {
  const cartList = ref([])
  const useStore = useUserStore()
  const isLogin = computed(() => useStore.userInfo.token)

  const updateNewList = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.result
  }
  const addCart = async (goods) => {
    // 添加购物车操作
    // 已添加过  count + 1
    // 没有添加过  直接 push
    // 思路：通过匹配传递过来的商品对象中的skuIdi能不能在cartList中找到，找到了就是添加过
    const { skuId, count } = goods
    if (isLogin.value) {
      // 有登录的逻辑
      await insertCartAPI({ skuId, count })
      const res = await findNewCartListAPI()
      cartList.value = res.result
    } else {
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        item.count++
      } else {
        cartList.value.push(goods)
      }
    }
  }
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      const res = await findNewCartListAPI()
      cartList.value = res.result
    } else {
      //1.找到要删除项的下标值-splice
      // const idx = cartList.value.findIndex((item) => item.skuId === skuId)
      // cartList.value.splice(idx,1)

      //2. 使用数组的过滤方法-filter
      cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
    }

  }

  // 清除购物车
  const clearCart = () => {
    cartList.value = []
  }
  // 单选功能
  const singleCheck = (i, selected) => {
    const item = cartList.value.find((item) => item.skuId === i.skuId)
    item.selected = selected
  }
  // 全选功能
  const allCheck = (selected) => {
    cartList.value.forEach((item) => item.selected = selected)
  }

  // 计算属性
  // 1.总的数量 所有项的count之和
  const allCount = computed(() => cartList.value.reduce((sum, item) => sum + item.count, 0))
  // 2.总价 所有项的count*price 之和
  const allPrice = computed(() => cartList.value.reduce((sum, item) => sum + item.count * item.price, 0))

  // 是否全选
  const isAll = computed(() => cartList.value.every((item) => item.selected))

  // 已选择数量
  const selectedCount = computed(() => cartList.value.filter((item) => item.selected).reduce((sum, item) => sum + item.count, 0))
  // 已选择商品价钱合计
  const selectedPrice = computed(() => cartList.value.filter((item) => item.selected).reduce((sum, item) => sum + item.count * item.price, 0))
  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    singleCheck,
    isAll,
    allCheck,
    selectedCount,
    selectedPrice,
    clearCart,
    findNewCartListAPI,
    updateNewList
  }
}, {
  // pinia设置自动本地存储
  persist: true
})